package com.faradel.pharmapp.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;

public abstract class GenericDAOImpl<T, PK extends Serializable> implements GenericDAO<T, PK>
{
    private Class<T> entity;

    @Resource
    protected SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
    }

    @SuppressWarnings("unchecked")
    public GenericDAOImpl()
    {
        entity = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> selectAll()
    {
        return (List<T>) this.sessionFactory.getCurrentSession().createQuery("from " + entity.getName()).list();
    }

    @Override
    public void save(T entity)
    {
        this.sessionFactory.getCurrentSession().save(entity);
    }

    @Override
    public void update(T entity)
    {
        this.sessionFactory.getCurrentSession().update(entity);
    }

    @Override
    public void delete(T entity)
    {
        this.sessionFactory.getCurrentSession().delete(entity);
    }

    @Override
    public T get(PK id)
    {
        @SuppressWarnings("unchecked")
        T ent = (T) this.sessionFactory.getCurrentSession().get(entity, id);
        return ent;
    }

}
